<?php

namespace System\Model;

use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Sql;
use System\Model\Imagespro;

class ImagesTable extends AbstractTableGateway {

    protected $table = "tblimages";
    protected $sql;

    public function __construct(Adapter $adapter) {
        $this->adapter = $adapter;
        $this->resultSetPrototype = new ResultSet();
        $this->resultSetPrototype->setArrayObjectPrototype(new Imagespro());
        $this->initialize();
        $this->sql = new Sql($this->adapter);
    }

    public function loadDir() {
        $sqlEx = $this->sql->select();
        $sqlEx->from($this->table);
        $sqlEx->columns(array("imt_Dir" => "imt_Dir"));
        $sqlEx->group(array("imt_Dir"));
        $sqlEx->order('img_Id DESC');
        $pst = $this->sql->prepareStatementForSqlObject($sqlEx);
        $resultSet = $pst->execute();
        $data = array();
        foreach ($resultSet as $result) {
            $data[] = $result;
        }
        return $data;
    }

    public function loadfile($dir) {
        $sqlEx = $this->sql->select();
        $sqlEx->from($this->table);
        $sqlEx->columns(array(
            "img_Id" => "img_Id",
            "img_thumb" => "img_thumb",
        ));
        $sqlEx->where(array("imt_Dir" => $dir));
        $sqlEx->order('img_Id DESC');
        $pst = $this->sql->prepareStatementForSqlObject($sqlEx);
        $resultSet = $pst->execute();
        $data = array();
        foreach ($resultSet as $result) {
            $data[] = $result;
        }
        return $data;
    }

    public function delfile($fileId) {
        $sqlEx = $this->sql->select();
        $sqlEx->from($this->table);
        $sqlEx->columns(array(
            "img_Url" => "img_Url",
            "img_thumb" => "img_thumb",
            "img_thumbdetail" => "img_thumbdetail",
        ));
        $sqlEx->where(array("img_Id" => $fileId));
        $pst = $this->sql->prepareStatementForSqlObject($sqlEx);
        $resultSet = $pst->execute();
        $data = $resultSet->current();
        $dirpath = str_replace("\\", "/", APPLICATION_PATH . "/public/");
        @unlink($dirpath . $data["img_Url"]);
        @unlink($dirpath . $data["img_thumb"]);
        @unlink($dirpath . $data["img_thumbdetail"]);
        $sqlExDel = $this->sql->delete();
        $sqlExDel->from($this->table);
        $sqlExDel->where(array("img_Id" => $fileId));
        $pstdel = $this->sql->prepareStatementForSqlObject($sqlExDel);
        $pstdel->execute();
    }

    public function addimg($data) {
        $sqlEx = $this->sql->insert();
        $sqlEx->into($this->table);
        $sqlEx->values($data);
        $pst = $this->sql->prepareStatementForSqlObject($sqlEx);
        $pst->execute();
    }

}
